package com.share.auth.service;

import com.share.common.core.constant.MessageConstant;
import com.share.common.core.constant.SecurityConstants;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.StringUtils;
import com.share.common.core.utils.ip.IpUtils;
import com.share.system.api.model.LoginUser;
import com.share.user.api.RemoteUserService;
import com.share.user.domain.UserInfo;
import com.share.user.domain.UpdateUserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Component
public class H5LoginService {


    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 微信登录
     * @param code
     * @return
     */
    public LoginUser login(String code) {
        //1 判断code是否为空
        if (StringUtils.isEmpty(code)){
            throw new ServiceException(MessageConstant.DATA_IS_EMPTY);
        }

        //2 拿code进行远程调用完成登录，返回userInfo
        R<UserInfo> userInfoR = remoteUserService.wxLogin(code);
        UserInfo userInfo = userInfoR.getData();

        //3 判段返回userInfo是否为空
        if (userInfo == null){
            throw new ServiceException(MessageConstant.DATA_IS_EMPTY);
        }

        //4 判断账号是否为禁用
        String status = userInfo.getStatus();
        if ("2".equals(status)){
            throw new ServiceException(MessageConstant.ACCOUNT_DISABLED);
        }

        //5 封装数据到LoginUser对象里面
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
        loginUser.setUsername(userInfo.getWxOpenId());
        loginUser.setStatus(userInfo.getStatus()+"");


        //更新登录信息
        UpdateUserLogin updateUserLogin = new UpdateUserLogin();
        updateUserLogin.setUserId(userInfo.getId());
        updateUserLogin.setLastLoginIp(IpUtils.getIpAddr());
        updateUserLogin.setLastLoginTime(new Date());
        remoteUserService.updateUserLogin(updateUserLogin);

        //6 返回数据
        return loginUser;
    }
}
